package org.yjy.sys.config.sqlsource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 人信息源配置
 */
//表示这是一个配置类
@Configuration
//进行mapper扫描
@MapperScan(basePackages = {"org.yjy.sys.dao.account"},
        sqlSessionFactoryRef = "accountSqlSessionFactory")
public class ByAccountSourceConfig {


    /**
     * 配置一个数据源的bean
     *
     * @return
     */
    @Bean(name = "accountDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.accountdb")
    public DataSource accountDbDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置SqlSessionFactory
     * 当我们注入的是相同类型的接口的bean时，
     * 可以通过Qualifier注解来区分具体是哪一个bean进行注入
     *  <bean id=  calsss></bean>
     * @param accountdbDataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "accountSqlSessionFactory")
    public SqlSessionFactory accountDbSqlSessionFactory(@Qualifier("accountDataSource") DataSource accountdbDataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //设置数据源
        sqlSessionFactoryBean.setDataSource(accountdbDataSource);
        //设置Mybatis配置，这里设置了驼峰命名配置
        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(config);
        //设置mapper.xml的所在目录
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:dao/cmp_account/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 配置SqlSessionTemplate
     *
     * @param accountdbSqlSessionFactory
     * @return
     */
    @Bean(name = "accountSqlSessionTemplate")
    public SqlSessionTemplate accountDbSqlSessionTemplate(@Qualifier("accountSqlSessionFactory") SqlSessionFactory accountdbSqlSessionFactory) {
        return new SqlSessionTemplate(accountdbSqlSessionFactory);
    }
}
